
/* 创建工具对象 */
var util = {}

/**
 * 工具，允许多次onload不被覆盖
 * @param {方法} func
 */
util.addLoadEvent = function(func) {
  var oldonload = window.onload
  if (typeof window.onload != 'function') {
    window.onload = func
  } else {
    window.onload = function() {
      oldonload()
      func()
    }
  }
}

/**
 * 工具，兼容的方式添加事件
 * @param {单个DOM节点} dom
 * @param {事件名} eventName
 * @param {事件方法} func
 * @param {是否捕获} useCapture
 */
util.addEvent = function(dom, eventName, func, useCapture) {
  if (window.attachEvent) {
    dom.attachEvent('on' + eventName, func)
  } else if (window.addEventListener) {
    if (useCapture != undefined && useCapture === true) {
      dom.addEventListener(eventName, func, true)
    } else {
      dom.addEventListener(eventName, func, false)
    }
  }
}

/**
 * 工具，DOM添加某个class
 * @param {单个DOM节点} dom
 * @param {class名} className
 */
util.addClass = function(dom, className) {
  if (!util.hasClass(dom, className)) {
    var c = dom.className || ''
    dom.className = c + ' ' + className
    dom.className = util.trim(dom.className)
  }
}

/**
 * 工具，DOM是否有某个class
 * @param {单个DOM节点} dom
 * @param {class名} className
 */
util.hasClass = function(dom, className) {
  var list = (dom.className || '').split(/\s+/)
  for (var i = 0; i < list.length; i++) {
    if (list[i] == className) return true
  }
  return false
}

/**
 * 工具，DOM删除某个class
 * @param {单个DOM节点} dom
 * @param {class名} className
 */
util.removeClass = function(dom, className) {
  if (util.hasClass(dom, className)) {
    var list = (dom.className || '').split(/\s+/)
    var newName = ''
    for (var i = 0; i < list.length; i++) {
      if (list[i] != className) newName = newName + ' ' + list[i]
    }
    dom.className = util.trim(newName)
  }
}

/**
 * 工具，DOM切换某个class
 * @param {单个DOM节点} dom
 * @param {class名} className
 */
util.toggleClass = function(dom, className) {
  if (util.hasClass(dom, className)) {
    util.removeClass(dom, className)
  } else {
    util.addClass(dom, className)
  }
}

/**
 * 工具，兼容问题，某些OPPO手机不支持ES5的trim方法
 * @param {字符串} str
 */
util.trim = function(str) {
  return str.replace(/^\s+|\s+$/g, '')
}

/**
 * 工具，转换实体字符防止XSS
 * @param {字符串} str
 */
util.encodeHtml = function(html) {
  var o = document.createElement('div')
  o.innerText = html
  var temp = o.innerHTML
  o = null
  return temp
}


/* 加载 md5 文件 */
var md5_script = document.createElement("script");
md5_script.type = "text/javascript";
md5_script.src = "md5.js";
document.head.appendChild(md5_script);

/* 加载 css 样式文件 */
var css_link = document.createElement("link");
css_link.type = "text/css";
css_link.rel = "stylesheet"
css_link.href = "blog.css";
document.head.appendChild(css_link);


/* 创建 HTTP 客户端，以请求网络数据 */
var requests = {}

requests.new_request = function() {
    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        try {
            // Internet Explorer
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
    return xmlHttp;
}

requests.urlencode = function(params) {
    var query = "";
    for (var key in params) {
        if (query != "") {
            query += "&";
        }
        query += key + "=" + encodeURIComponent(params[key]);
    }
    return query
}

requests._request = function(options) {
    var method = (options.method || "GET").toUpperCase();
    var data = options.data;
    var url = options.url;
    var params = options.params;
    if (params) {
        if (url.indexOf('?') < 0) {
            url += '?';
        }
        url += this.urlencode(params);
    }

    var xhr = this.new_request();
    xhr.open(method, url, true);
    if (data) {
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    }
    xhr.onreadystatechange = function(){
        var XMLHttpReq = xhr;
        /**
         XMLHttpReq.readyState
         0: 请求未初始化
         1: 服务器连接已建立
         2: 请求已接收
         3: 请求处理中
         4: 请求已完成，且响应已就绪
        **/
        if (XMLHttpReq.readyState == 4) {
            if (XMLHttpReq.status == 200) {
                var on_success = options.on_success;
                if (on_success) {
                    on_success(XMLHttpReq.responseText)
                }
            } else {
                var on_error = options.on_error;
                if (on_error) {
                    on_error(XMLHttpReq.status);
                }
                console.error("http status " + XMLHttpReq.status);
            }
        }
    };

    if (data) {
        var form_data = this.urlencode(data);
        xhr.send(form_data);
    } else {
        xhr.send();
    }
}

requests.get = function(options) {
    options.method = "GET";
    this._request(options);
}

requests.post = function(options) {
    options.method = "POST";
    this._request(options);
}


/* 创建留言板对象 */
var msgboard = {
    page_url: window.location.hostname + window.location.pathname,
    msg_server: "http://localhost:8006",
    msg_page_size: 10,  // 每页大小
    msg_page_index: 0,  // 已加载页码
}

msgboard.create_msg_page = function() {
    container = document.getElementById('msgboard');
    if (container.className.length > 0) {
        container.className += " ";
    }
    container.className += "container page-chat animation-fade-up";

    create_input = function(attrs) {
        input = document.createElement("input");
        for (var key in attrs) {
            input.setAttribute(key, attrs[key]);
        }
        input.autocomplete = "off";
        return input;
    }

    name_input = create_input({"type": "text", "placeholder": "昵称"});
    email_input = create_input({"type": "email", "placeholder": "邮箱"});
    site_input = create_input({"type": "text", "placeholder": "站点(http://)"});

    textarea = document.createElement("textarea");
    textarea.row = "4";
    textarea.placeholder = "请填写你的留言，小于200字";

    submit_button = document.createElement("span");
    submit_button.innerText = "提交";
    submit_button.className = "select-none page-chat-submit";

    form = document.createElement("form");
    form.appendChild(name_input);
    form.appendChild(email_input);
    form.appendChild(site_input);
    form.appendChild(textarea);
    form.appendChild(submit_button);

    msg_list = document.createElement("ul");
    msg_list.className = "page-chat-list"

    load_button = document.createElement("span")
    load_button.className = "page-chat-load select-none"
    load_button_container = document.createElement("div")
    load_button_container.className = "page-chat-load-container"
    load_button_container.appendChild(load_button)

    container.appendChild(form)
    container.appendChild(msg_list)
    container.appendChild(load_button_container)

    msg_template = '' +
        '<li>' +
        '<div class="info">' +
        '<img class="head" {blank}src="http://www.gravatar.com/avatar/{emailMD5}" />' +
        '<a class="name name-{hasSite}" target="_blank" href="{site}">{name}</a>' +
        '<div class="date"><span>{date}</span></div>' +
        '</div>' +
        '<div class="content">{content}</div>' +
        '</li>'

    this.msg_list = msg_list
    this.load_button = load_button
    this.submit_button = submit_button
    this.templet = msg_template
}

msgboard.load_message = function() {
    this.msg_page_index += 1;
    requests.get({
        url: this.msg_server + "/youngle/comment/list",
        params: {page: this.msg_page_index, size: this.msg_page_size},
        on_success: function(response) {
            var that = msgboard;
            var load_button = that.load_button;
            var resp = JSON.parse(response);
            if (Number(resp.code) == 0) {
                var messages = resp.data.comments;
                var msg_count = messages.length;
                if (msg_count == 0) {
                    load_button.parentNode.parentNode.removeChild(load_button.parentNode);
                } else {
                    load_button.innerText = '加载更多'
                    for(var i = 0; i < msg_count; i++){
                        that.render_one_message(messages[i]);
                    }
                }
            } else {
                load_button.innerText = '查询评论失败';
                console.error("respone code is abnormal: " + resp.code);
            }
        },
        on_error: function() {
            msgboard.load_button.innerText = '无法正常连接服务';
        }
    })
}

msgboard.render_one_message = function(message) {
    // 把一个评论放入到页面中
    var html = this.templet;
    html = html.replace('{blank}', '');

    var user_email = util.md5(message.user_email || '');
    var user_name = message.user_name || '';
    var user_website = message.user_website || '';
    var content = util.encodeHtml(message.content || '');
    var date = (message.add_time || '').substr(0, 10);

    html = html.replace(
        '{emailMD5}', user_email
    ).replace(
        '{name}',  user_name
    ).replace(
        '{content}', content
    ).replace(
        '{date}', date
    );
    if (user_website == '') {
        html = html.replace('{site}', 'javascript:void(0);');
        html = html.replace('{hasSite}', 'false');
    } else {
        html = html.replace('{site}', user_website);
        html = html.replace('{hasSite}', 'true');
    }

    var div_obj = document.createElement('div');
    div_obj.innerHTML = html;
    this.msg_list.appendChild(div_obj.children[0]);
    div_obj = null;
}

msgboard.submit_message = function() {
    var email_check = new RegExp(
        '^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$'
    )
    var url_check = (new RegExp('^https?://.+..+'))

    var dom_form = document.getElementsByTagName('form')[0]
    var dom_name = dom_form.getElementsByTagName('input')[0]
    var dom_email = dom_form.getElementsByTagName('input')[1]
    var dom_site = dom_form.getElementsByTagName('input')[2]
    var dom_content = dom_form.getElementsByTagName('textarea')[0]

    var name = util.trim(dom_name.value)
    var email = util.trim(dom_email.value)
    var site = util.trim(dom_site.value)
    var content = util.trim(dom_content.value)

    if (name == '' || name.length > 20) {
        alert('昵称不能为空且长度不能超过 20');
        return;
    }
    if (name.toLowerCase().indexOf('huoty') != -1) {
        alert('昵称已被占用，请使用其他昵称');
        return;
    }
    if (email == '' || email.length > 50) {
        alert('邮箱不能为空且成都不能超过 50');
        return;
    }
    if (!email_check.test(email)) {
        alert('邮箱格式不正确: ' + email);
        return;
    }
    if (site != '' && (site.length > 120 || !url_check.test(site))) {
        alert('站点长度大于 120 或格式错误');
        return;
    }
    if (content == '' || content.length > 200) {
        alert('内容为空或长度大于 200');
        return;
    }

    requests.post({
        url: this.msg_server + "/youngle/comment/add",
        data: {
            user: name,
            email: email,
            website: site,
            content: content,
        },
        on_success: function(response) {
            var resp = JSON.parse(response);
            if (Number(resp.code) == 0) {
                alert('留言成功');
            } else {
                console.error("respone code is abnormal: " + resp.code +
                              ", msg: " + resp.msg);
                alert('提交评论失败: ' + resp.msg);
            }
        },
        on_error: function() {
            alert('提交评论失败');
        }
    })
}

util.addLoadEvent(function() {
    // 创建留言板
    msgboard.create_msg_page();

    // 先加载第一页评论内容
    msgboard.load_message();

    // 加载更多评论
    util.addEvent(msgboard.load_button, 'click', function() {
        if (msgboard.load_button.innerText == '加载更多') {
            msgboard.load_button.innerText = '评论拉取中';
            msgboard.load_message();
        }
    })

    // 提交评论
    //提交评论
    util.addEvent(msgboard.submit_button, 'click', function() {
        msgboard.submit_message();
    })
})
